<?php

namespace app\controllers;

use app\models\order\Order;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\redis\api\Error;
use app\redis\api\RunLong;
use wsl\ip2location\Ip2Location;

/**
 * Class SiteController
 * @package app\controllers
 */
class SiteController extends Controller
{
    /**
     * api error handler 404
     */
    public function actionError()
    {
        /**
         * Save run error logs
         */
        $error = new Error();
        $error->url = \Yii::$app->request->getUrl();
        $error->ip = \Yii::$app->request->userIP;
        $error->create_time = date('Y-m-d H:i:s');

        // ip => area
        $ipLocation = new Ip2Location();
        $address = $ipLocation->getLocation($error->ip);

        $error->country = $address['country'];
        $error->area = $address['area'];
        $error->save();

        // return $this->fail('Not found 404');
        return $this->fail('请求接口不存在');
    }

    /**
     * 404 errors list
     *
     * @return \yii\web\Response
     */
    public function actionErrors()
    {
        return $this->success(Error::getList());
    }

    /**
     * run long list
     *
     * @return \yii\web\Response
     */
    public function actionLong()
    {
        return $this->success(RunLong::getList());
    }

    /**
     * default index page
     *
     * @return string
     */
    public function actionIndex()
    {
        return 'welcome to zou wx 2024      !!!';
    }

    // 删除佣金
    protected function actionRemove()
    {
        $sn = $this->get('sn');

        $order = Order::findOne(['sn' => trim($sn)]);
        if ($order) {
            $commission = UserCommission::find()
                ->where(['order_id' => $order->id])
                ->all();

            foreach ($commission as $c) {
                if ($c->status == 1) {

                    $account = UserAccount::findOne(['user_id' => $c->user_id]);
                    if ($account) {
                        $account->balance -= $c->balance;
                        $account->save();

                        echo $account->user_id, ' - ', $c->balance, "\n";

                        $c->delete();
                    }


                }
            }

            $order->delete();
        } else {
            echo  '不存在或者已经操作过了';
        }
    }

    private function actionXyz()
    {
        $commission = UserCommission::find()
            ->where(['order_id' => 2563])
            ->all();

        foreach ($commission as $c) {
            $account = UserAccount::findOne(['user_id' => $c->user_id]);
            if ($account && $account->await_balance >= $c->balance) {
                $account->await_balance -= $c->balance;
                $account->save();

                echo $account->user_id, ' - ', $c->balance, "\n";

                // $c->delete();
            }
        }
    }
}
